<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

class UserAppController extends Controller
{
    public function index($userId){
        $appUserResult = DB::table("ap_app_user")
            ->select("ap_app.id","ap_app.name","ap_app.version_name","ap_app.description","ap_app.icon","ap_app.color","ap_app.url","ap_app.need_verified",
                "ap_app_user.is_inform","ap_app_user.weight","ap_app_user.created_at")
            ->join("ap_app","ap_app.id","=","ap_app_user.app_id")
            ->where("ap_app_user.user_id",$userId)
            ->where("ap_app_user.is_deleted",false)
            ->where("ap_app.is_public",true)
            ->orderBy("ap_app_user.weight","ASC")
            ->orderBy("ap_app_user.created_at","ASC")
            ->get();

        return $this->jsonResponse(false,$appUserResult);
    }

    public function store($userId,$appId){
        $appUserResult = DB::table("ap_app_user")
            ->select("id","is_deleted")
            ->where("user_id",$userId)
            ->where("app_id",$appId)
            ->first();

        if(!empty($appUserResult) && !$appUserResult->is_deleted)
            return $this::jsonResponse(true,[],"应用已绑定。");

        $eventHookData = [
            "app_id"=>$appId,
            "event" =>"focuse",
            "data"  =>[
                "user_id"=>$userId
            ]
        ]; 
        $this::mq("appevent",$eventHookData);

        if(!empty($appUserResult)){
            DB::table("ap_app_user")->where("id",$appUserResult->id)->update(["is_deleted"=>false]);
            return $this::jsonResponse(false,[],"应用重新绑定成功。");
        }

        $insertData = [
            "app_id"  => $appId,
            "user_id" => $userId
        ];
        $appUserId = DB::table("ap_app_user")->insertGetId($insertData);
        return $this->jsonResponse(false,$appUserId);
    }


    public function storeDefault($userId){
        $appUserResult = DB::table("ap_app_user")
            ->select("app_id")
            ->where("user_id",$userId)
            ->get();

        $appIds = [];
        foreach ($appUserResult as $key => $value) {
            $appIds[] = $value->app_id;
        }

        $appDefaultResult = DB::table("ap_app")
            ->select("id","weight")
            ->where("is_default",true)
            ->where("is_public",true)
            ->orderBy("weight","ASC")
            ->get();

        $insertData = [];
        foreach ($appDefaultResult as $key => $value) {
            if(!in_array($value->id,$appIds)){
                $insertData[] = [
                    "app_id" => $value->id,
                    "user_id"=> $userId,
                    "weight" => $value->weight
                ];
            }
        }

        if(empty($insertData))
            return $this::jsonResponse(true,[],"无可保存数据。");

        DB::table("ap_app_user")->insert($insertData);

        foreach ($insertData as $value) {
            $eventHookData = [
                "app_id"=>$value["app_id"],
                "event" =>"focuse",
                "data"  =>[
                    "user_id"=>$value["user_id"]
                ]
            ];
            $this::mq("appevent",$eventHookData);
        }

        return $this->jsonResponse(false,true);
    }
    
    public function update(Request $request, $userId, $appId){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'is_inform' => 'boolean'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        $updateData = [];

        if(isset($input["is_inform"]))
            $updateData["is_inform"] = $input["is_inform"];

        if(empty($updateData))
            return $this->jsonResponse(true,[],"无更新数据。");

        $appUserResult = DB::table("ap_app_user")
        	->where("app_id",$appId)
        	->where("user_id",$userId)
        	->update($updateData);

        if($appUserResult && isset($updateData["is_inform"])){
            $eventHookData = [
                "app_id"=>$appId,
                "event" =>$updateData["is_inform"]?"unshield":"shield",
                "data"  =>[
                    "user_id"=>$userId
                ]
            ]; 
            $this::mq("appevent",$eventHookData);
        }

        return $this->jsonResponse(false,$appUserResult);
    }

    public function destroy($userId,$appId){
        $appUserResult = DB::table("ap_app_user")
        	->where("app_id",$appId)
        	->where("user_id",$userId)
        	->update(["is_deleted"=>true]);

        if($appUserResult){
            $eventHookData = [
                "app_id"=>$appId,
                "event" =>"unfocuse",
                "data"  =>[
                    "user_id"=>$userId
                ]
            ]; 
            $this::mq("appevent",$eventHookData);
        }

        return $this->jsonResponse(false,$appUserResult);
    }

    public function updateOrder(Request $request, $userId){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'app_id'    => 'required|array'
            ]
        );
        if($validator->fails()){
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        }

        foreach ($input["app_id"] as $key => $appId) {
            if(!empty($appId)){
                $appUserResult = DB::table("ap_app_user")
                    ->where("app_id",$appId)
                    ->where("user_id",$userId)
                    ->update(["weight"=>(1+$key)]);
            }
        }
        return $this->jsonResponse(false,true);
    }

}